﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using FbKPI.Facade;
using FbKPI.Model;
using FbKPI.Facade.Validator;
using System.Transactions;

namespace FBKPI.Pages
{
    public partial class InputKPIAssignDetailPage : System.Web.UI.Page
    {
        protected override void OnPreRender(EventArgs e)
        {
            //ViewState["update"] = Session["update"];
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                //Session["update"] = Server.UrlEncode(System.DateTime.Now.ToString());

                int ID = Convert.ToInt32(Request.QueryString["KPI"]);
                int KPIAssignDetailID = Convert.ToInt32(Request.QueryString["KPIAssignDetail"]);

                if (ID != 0)
                {
                    KPIFacade df = new KPIFacade();
                    KPI KPIs = df.GetKPIByID(ID);

                    if (KPIs != null)
                    {
                        hfKpiID.Value = KPIs.ID.ToString();
                        txt_kpidescription.Text = KPIs.Description;
                        chk_active.Checked = KPIs.isActive;
                        txt_kpigroup.Text = KPIs.GroupKPI == null ? "" : KPIs.GroupKPI.Description;
                        txt_kpicategory.Text = KPIs.CategoryKPI == null ? "" : KPIs.CategoryKPI.Description;
                        txt_kpitype.Text = KPIs.TypeKPI == null ? "" : KPIs.TypeKPI.Description;
                        txt_kpisubtype.Text = KPIs.SubTypeKPI == null ? "" : KPIs.SubTypeKPI.Description;
                        txt_kpiuom.Text = KPIs.UoM == null ? "" : KPIs.UoM.Description;
                        txt_kpiuommax.Text = KPIs.UoMDetailMax == null ? "" : KPIs.UoMDetailMax.Description + " || " + KPIs.UoMDetailMax.ListValue;
                        txt_kpiuommin.Text = KPIs.UoMDetailMin == null ? "" : KPIs.UoMDetailMin.Description + " || " + KPIs.UoMDetailMin.ListValue;
                        txt_kpiyear.Text = KPIs.Year.ToString();
                        txt_weight.Text = KPIs.Weight.ToString();
                        txt_kpiperiode.Text = KPIs.Periode;
                        txt_polarization.Text = KPIs.Polarization;
                        txt_uomformat.Value = KPIs.UoM.Format.ToString();
                        lblLock.Text = KPIs.isLockWeight == false ? "No" : "Yes";
                        if (KPIs.isLockWeight)
                        {
                            txtWeightAssign.Text = KPIs.Weight.ToString();
                        }
                        else
                        {
                            txtWeightAssign.ReadOnly = false;
                            txtWeightAssign.Text = KPIs.Weight.ToString();

                            if (KPIs.AssignWeight == "1")
                                txtScoreWeight.Text = "None";

                            if (KPIs.AssignWeight == "2")
                                txtScoreWeight.Text = "greater than or equal";

                        }
                    }
                }
                else if (KPIAssignDetailID != 0)
                {
                    KPIAssignDetailFacade df = new KPIAssignDetailFacade();
                    KPIAssignDetail KPIs = df.GetKPIAssignDetailByID(KPIAssignDetailID);

                    if (KPIs != null)
                    {
                        txt_kpidescription.Text = KPIs.KPI.Description;
                        chk_active.Checked = KPIs.KPI.isActive;
                       
                        txt_kpigroup.Text = KPIs.KPI.GroupKPI == null ? "" : KPIs.KPI.GroupKPI.Description;
                        txt_kpicategory.Text = KPIs.KPI.CategoryKPI == null ? "" : KPIs.KPI.CategoryKPI.Description;
                        txt_kpitype.Text = KPIs.KPI.TypeKPI == null ? "" : KPIs.KPI.TypeKPI.Description;
                        txt_kpisubtype.Text = KPIs.KPI.SubTypeKPI == null ? "" : KPIs.KPI.SubTypeKPI.Description;
                        txt_kpiuom.Text = KPIs.KPI.UoM == null ? "" : KPIs.KPI.UoM.Description;
                        txt_kpiuommax.Text = KPIs.KPI.UoMDetailMax == null ? "" : KPIs.KPI.UoMDetailMax.Description + " || " + KPIs.KPI.UoMDetailMax.ListValue;
                        txt_kpiuommin.Text = KPIs.KPI.UoMDetailMin == null ? "" : KPIs.KPI.UoMDetailMin.Description + " || " + KPIs.KPI.UoMDetailMin.ListValue;
                        txt_kpiyear.Text = KPIs.KPI.Year.ToString();
                        txt_weight.Text = KPIs.KPI.Weight.ToString();
                        txt_kpiperiode.Text = KPIs.KPI.Periode;
                        txt_polarization.Text = KPIs.KPI.Polarization;
                        txt_uomformat.Value = KPIs.KPI.UoM.Format.ToString();

                        txt_assignid.Text = KPIAssignDetailID.ToString();
                        txt_employeeid.Value = KPIs.Employee.ID.ToString();
                        txt_employee.Text = KPIs.Employee.FirstName + "  "+ KPIs.Employee.LastName;
                        chk_assingisactive.Checked = KPIs.isActive;

                        //chkLockWeight.Checked = KPIs.KPI.isLockWeight;
                        lblLock.Text = KPIs.KPI.isLockWeight == false ? "No" : "Yes";
                        if (KPIs.KPI.isLockWeight)
                        {
                            txtWeightAssign.Text = KPIs.Weight.ToString();
                        }
                        else
                        {
                            txtWeightAssign.ReadOnly = false;
                            txtWeightAssign.Text = KPIs.Weight.ToString();

                            if (KPIs.KPI.AssignWeight == "1")
                                txtScoreWeight.Text = "None";

                            if (KPIs.KPI.AssignWeight == "2")
                                txtScoreWeight.Text = "greater than or equal";

                        }
                    }
                }
            }
        }
        protected void SaveAction(object sender, EventArgs e)
        {
            //if (Session["update"].ToString() == ViewState["update"].ToString())
            //{
            //    if (txt_assignid.Text == "0")
            //    {
            //        int KPIID = Convert.ToInt32(Request.QueryString["KPI"]);
            //        string msg = "OK";

            //        Employee CurrUser = new EmployeeFacade().GetEmployeeByID(Convert.ToInt32(HttpContext.Current.Request.QueryString["User"]));
            //        Employee AssignTo = null;

            //        if (txt_employeeid.Value != string.Empty)
            //        {
                        
            //            AssignTo = new EmployeeFacade().GetEmployeeByID(Convert.ToInt32(txt_employeeid.Value));
            //        }
            //        else
            //        {
            //            msg = "Please select employee to be assigned";
            //            Response.Write("<script>alert('" + msg + "');</script>");
            //        }

            //        if (AssignTo != null)
            //        {
            //            string jumlahRow = new KPIAssignDetailFacade().BeforeAssignKPI(KPIID, AssignTo.ID);
            //            if (Convert.ToInt16(jumlahRow) != 0)
            //            {
            //                msg = "Assign KPI tidak berhasil, Employee tersebut sudah pernah di Assign KPI !";

            //                Response.Write("<script>alert('" + msg + "');</script>");
            //                return;
            //                //return;
            //            }

                       

            //            KPIFacade df = new KPIFacade();
            //            KPI KPIs = df.GetKPIByID(KPIID);

            //            //WeightValidator wv = new WeightValidator();
            //            //msg = wv.ValidateWeight(CurrUser, ka, KPIs.Year);

            //            if (!KPIs.isLockWeight)
            //            {
            //                if (KPIs.AssignWeight == "2")
            //                {
            //                    if (Convert.ToInt32(txtWeightAssign.Text) < Convert.ToInt32(txt_weight.Text))
            //                    {
            //                        msg = "Nilai Weight Assign :"+ txtWeightAssign.Text +" harus lebih besar/sama dengan weight KPI :"+txt_weight.Text+" !";

            //                        Response.Write("<script>alert('" + msg + "');</script>");
            //                        return;
            //                    }
            //                }
            //            }


            //            KPIValidator KPIValidator = new KPIValidator();
            //            msg = KPIValidator.ValidateKPIParentAndChildAssignment(AssignTo, KPIs);

            //            if (msg == "OK")
            //            {
            //                IList<KPIAssign> KPIAssigns = new KPIAssignFacade().GetAllKPIAssignsByKPIID(KPIID);

            //                //KPIAssign Existing = KPIAssigns.Where(x => x.CreateBy == CurrUser.Email && x.isActive &&
            //                //    x.SubBranch.ID == CurrUser.SubBranch.ID && x.Verifier.ID == CurrUser.ID && x.Weight == KPIs.Weight).FirstOrDefault();


            //                KPIAssign Existing =  KPIAssigns.Where(x => x.isActive).FirstOrDefault();// &&
            //                ///    x.SubBranch.ID == CurrUser.SubBranch.ID && x.Verifier.ID == CurrUser.ID && x.Weight == KPIs.Weight).FirstOrDefault();

            //                if (Existing == null)
            //                {
            //                    KPIAssign ka = new KPIAssign()
            //                    {
            //                        ID = 0,
            //                        isActive = true,
            //                        KPI = KPIs,
            //                        Location = CurrUser.SubBranch.Location,
            //                        ManualCalculation = KPIs.ManualCalculation,
            //                        Polarization = KPIs.Polarization,
            //                        RGM = CurrUser.SubBranch.Location.RGM,
            //                        SubBranch = CurrUser.SubBranch,
            //                        UoM = KPIs.UoM,
            //                        UoMDetailMax = KPIs.UoMDetailMax,
            //                        UoMDetailMin = KPIs.UoMDetailMin,
            //                        UoMEnableFlag = KPIs.UoMEnableFlag,
            //                        Verifier = CurrUser,
            //                        Weight = Convert.ToInt32(txtWeightAssign.Text),//; KPIs.Weight,
            //                        WeightEnableFlag = KPIs.WeightEnableFlag,
            //                        CreateBy = CurrUser.Email
            //                    };

            //                    //WeightValidator wv = new WeightValidator();
            //                   // msg = wv.ValidateWeight(CurrUser, ka, KPIs.Year);

            //                    if (msg == "OK")
            //                    {
            //                        using (TransactionScope trans = new TransactionScope(TransactionScopeOption.RequiresNew))
            //                        {
            //                            try
            //                            {
            //                                KPIAssignFacade kaf = new KPIAssignFacade();
            //                                msg = kaf.Save(ka);

            //                                if (msg.Contains("Success"))
            //                                {
            //                                    KPIAssign kasaved = new KPIAssignFacade().GetAllKPIAssignsByKPIID(KPIs.ID).Where(x => x.SubBranch.ID == CurrUser.SubBranch.ID && x.isActive && x.CreateBy == CurrUser.Email).FirstOrDefault();

            //                                    KPIAssignDetail kad = new KPIAssignDetail()
            //                                    {
            //                                        ID = 0,
            //                                        CreateBy = CurrUser.Email,
            //                                        Employee = AssignTo,
            //                                        isActive = true,
            //                                        KPI = KPIs,
            //                                        KPIAssign = kasaved,
            //                                        ManualCalculation = KPIs.ManualCalculation,
            //                                        Polarization = KPIs.Polarization,
            //                                        UoM = KPIs.UoM,
            //                                        UoMDetailMax = KPIs.UoMDetailMax,
            //                                        UoMDetailMin = KPIs.UoMDetailMin,
            //                                        UoMEnableFlag = KPIs.UoMEnableFlag,
            //                                        Weight = KPIs.Weight,
            //                                        WeightEnableFlag = KPIs.WeightEnableFlag,
            //                                        Mandatory = ddlMandatory.SelectedValue == "1" ? true : false,
            //                                        AssignBy = CurrUser.ID

            //                                    };

            //                                    KPIAssignDetailFacade kadf = new KPIAssignDetailFacade();
            //                                    msg = kadf.Save(kad);
            //                                    if (msg.Contains("Success"))
            //                                    {
            //                                        KPIs.LastModifiedBy = CurrUser.Email;
            //                                        KPIs.EmployeeIDVerifier = AssignTo.Supervisor;
            //                                        msg = new KPIFacade().UpateVerifierKPI(KPIs);
            //                                        Response.Write("<script>alert('" + msg + "');</script>");
            //                                    }
                                               
                                                
                                                
            //                                }
            //                            }
            //                            catch (Exception ex)
            //                            {
            //                                Tools.LogWriter.LogWriter logwriter = new Tools.LogWriter.LogWriter();
            //                                logwriter.WriteLog(msg, ex.StackTrace.ToString());
            //                                Response.Write("<script>alert('" + msg + "');</script>");
            //                            }
            //                            finally
            //                            {

            //                                trans.Complete();
            //                                trans.Dispose();
            //                                //Response.Redirect("~/Pages/KPIAssignDetailPage.aspx?user=" + Context.Request.Params["user"]);
            //                            }
            //                        }
            //                    }
            //                    else
            //                    {
            //                        Response.Write("<script>alert('" + msg + "');</script>");
            //                    }
            //                }
            //                else
            //                {
            //                    WeightValidator wv = new WeightValidator();
            //                    //msg = wv.ValidateWeight(CurrUser, Existing, KPIs.Year);
            //                    int Weight = 0;
            //                    if (txtWeightAssign.Text == "" || txtWeightAssign.Text == "0")
            //                        Weight = Existing.Weight;
            //                    else
            //                        Weight = Convert.ToInt32(txtWeightAssign.Text);

            //                    msg = wv.ValidateWeightDua(AssignTo,Weight, KPIs.Year);

            //                    if (msg == "OK")
            //                    {
            //                        KPIAssignDetail kad = new KPIAssignDetail()
            //                        {
            //                            ID = 0,
            //                            CreateBy = CurrUser.Email,
            //                            Employee = AssignTo,
            //                            isActive = true,
            //                            KPI = KPIs,
            //                            KPIAssign = Existing,
            //                            ManualCalculation = KPIs.ManualCalculation,
            //                            Polarization = KPIs.Polarization,
            //                            UoM = KPIs.UoM,
            //                            UoMDetailMax = KPIs.UoMDetailMax,
            //                            UoMDetailMin = KPIs.UoMDetailMin,
            //                            UoMEnableFlag = KPIs.UoMEnableFlag,
            //                            //Weight = KPIs.Weight,
            //                            WeightEnableFlag = KPIs.WeightEnableFlag,
            //                            Mandatory = ddlMandatory.SelectedValue=="1"?true:false,
            //                            Weight = Convert.ToInt32(txtWeightAssign.Text),
            //                            AssignBy = CurrUser.ID

            //                        };

            //                        using (TransactionScope trans = new TransactionScope(TransactionScopeOption.RequiresNew))
            //                        {
            //                            try
            //                            {
            //                                KPIAssignDetailFacade kadf = new KPIAssignDetailFacade();
            //                                msg = kadf.Save(kad);
                                           
            //                                if (msg.Contains("Success"))
            //                                {
            //                                    KPIs.LastModifiedBy = CurrUser.Email;
            //                                    KPIs.EmployeeIDVerifier = AssignTo.Supervisor;
            //                                    msg = new KPIFacade().UpateVerifierKPI(KPIs);
            //                                    Response.Write("<script>alert('" + msg + "');</script>");
            //                                }
                                            
                                           
            //                            }
            //                            catch (Exception ex)
            //                            {
            //                                Tools.LogWriter.LogWriter logwriter = new Tools.LogWriter.LogWriter();
            //                                logwriter.WriteLog(msg, ex.StackTrace.ToString());
            //                                Response.Write("<script>alert('" + msg + "');</script>");
            //                            }
            //                            finally
            //                            {
            //                                trans.Complete();
            //                                trans.Dispose();

            //                                //Response.Redirect("~/Pages/KPIAssignDetailPage.aspx?user=" + Context.Request.Params["user"]);
            //                            }
            //                        }
            //                    }
            //                    else
            //                    {
            //                        Response.Write("<script>alert('" + msg + "');</script>");
            //                    }
            //                }
            //            }
            //            else
            //            {
            //                Response.Write("<script>alert('" + msg + "');</script>");
            //            }
            //        }
            //    }
            //    //else
            //    //{
            //    //    string msg = "OK";
            //    //    KPIAssignDetail kad = new KPIAssignDetailFacade().GetKPIAssignDetailByID(Convert.ToInt32(txt_assignid.Text));
            //    //    Employee CurrUser = new EmployeeFacade().GetEmployeeByID(Convert.ToInt32(HttpContext.Current.Request.QueryString["User"]));
            //    //    Employee AssignTo = new EmployeeFacade().GetEmployeeByID(Convert.ToInt32(txt_employeeid.Value));

            //    //    if (!kad.KPI.isLockWeight)
            //    //    {
            //    //        if (kad.KPI.AssignWeight == "2")
            //    //        {
            //    //            if (Convert.ToInt32(txtWeightAssign.Text) < Convert.ToInt32(txt_weight.Text))
            //    //            {
            //    //                msg = "Nilai Weight Assign :" + txtWeightAssign.Text + " harus lebih besar/sama dengan weight KPI :" + txt_weight.Text + " !";
            //    //                Response.Write("<script>alert('" + msg + "');</script>");
            //    //                return;
            //    //            }
            //    //        }
            //    //    }

            //    //    KPIValidator KPIValidator = new KPIValidator();
            //    //    msg = KPIValidator.ValidateKPIParentAndChildAssignment(AssignTo, kad.KPI);

            //    //    if (msg == "OK")
            //    //    {
            //    //        WeightValidator wv = new WeightValidator();
            //    //        msg = wv.ValidateWeight(AssignTo, kad.KPIAssign, kad.KPI.Year);

            //    //        if (msg == "OK")
            //    //        {
            //    //            if (kad != null)
            //    //            {
            //    //                using (TransactionScope trans = new TransactionScope(TransactionScopeOption.RequiresNew))
            //    //                {
            //    //                    try
            //    //                    {
            //    //                        kad.Employee = AssignTo;
            //    //                        kad.LastModifiedBy = CurrUser.Email;
            //    //                        kad.Weight = Convert.ToInt32(txtWeightAssign.Text);
            //    //                        KPIAssignDetailFacade kadf = new KPIAssignDetailFacade();
            //    //                        msg = kadf.Save(kad);
            //    //                        Response.Write("<script>alert('" + msg + "');</script>");
            //    //                        Response.Redirect("~/Pages/KPIAssignDetailPage.aspx?user=" + Context.Request.Params["user"]);
            //    //                    }
            //    //                    catch (Exception ex)
            //    //                    {
            //    //                        Tools.LogWriter.LogWriter logwriter = new Tools.LogWriter.LogWriter();
            //    //                        logwriter.WriteLog(msg, ex.StackTrace.ToString());
            //    //                        Response.Write("<script>alert('" + msg + "');</script>");
            //    //                    }
            //    //                    finally
            //    //                    {
            //    //                        trans.Complete();
            //    //                        trans.Dispose();
            //    //                    }
            //    //                }
            //    //            }
            //    //        }
            //    //        else
            //    //        {
            //    //            Response.Write("<script>alert('" + msg + "');</script>");
            //    //        }
            //    //    }
            //    //    else
            //    //    {
            //    //        Response.Write("<script>alert('" + msg + "');</script>");
            //    //    }
            //    //}
            //    Session["update"] = Server.UrlEncode(System.DateTime.Now.ToString());
           // }
        }
    }
}